<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <el-form :inline="true" size="medium">
            <el-form-item>
              <el-button type="primary"  @click="showAddDialogForm">上传照片</el-button>
            </el-form-item>
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <!-- <el-form-item>
              <el-button type="primary" size="mini" @click="search">刷新</el-button>
            </el-form-item> -->
            <!-- <el-form-item>
              <el-button type="primary" size="mini" @click="handleExcelImp">excel导入</el-button>
            </el-form-item> -->
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <!-- <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="name"
        label="打包项目名称"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="carTypeName"
        label="车型类别"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="productTypeName1"
        label="一级分类"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="productTypeName2"
        label="二级分类"
        min-width="120">
      </el-table-column> -->
      <!-- <el-table-column
        prop="serialNumber"
        label="编号"
        min-width="120">
      </el-table-column> -->
      <!-- <el-table-column
        prop="itemName"
        label="包含检测项目"
        min-width="120">
      </el-table-column> -->
      <!-- <el-table-column
        prop="price"
        label="套餐价格"
        min-width="110">
      </el-table-column> -->
      <!-- <el-table-column
        prop="note"
        label="备注"
        min-width="200">
      </el-table-column> -->
      <!-- <el-table-column
        prop="address"
        label="操作"
        min-width="170">
        <template slot-scope="scope">

          <el-button size="mini" type="primary" @click="testGroupItems(scope.$index, scope.row)">查看</el-button>
          <el-button size="mini" type="primary"  @click="handleEdit(scope.$index, scope.row)">修改</el-button>

          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog :title="editForm.id==0?'新增':'修改'" :visible.sync="editFormVisible" width="700px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item label="员工编号" label-width="120px" prop="id">
          <el-input v-model="editForm.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传照片" label-width="120px" prop="">
        <el-upload
          class="avatar-uploader"
          :action="uploadActionUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"

          multiple
          :on-success="handleAvatarSuccess"
          :file-list="fileList"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
        </el-upload>
        </el-form-item>






        <!-- <el-form-item label="序号" label-width="100px" prop="serialNumber">
          <el-input v-model="editForm.serialNumber" autocomplete="off"></el-input>
        </el-form-item> -->

        <!-- <el-form-item label="检测项目" label-width="120px" prop="testItemIdListTemp">
          <el-select style="width: 100%;"
              v-model="editForm.testItemIdListTemp" filterable multiple placeholder="请选择">
              <el-option
                    v-for="item in testItemList"
                    :key="item.tId"
                    :label="item.serialNumber+':'+item.itemName"
                    :value="item.tId">
                  </el-option>
                  </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="套餐价格" label-width="100px" prop="price">
          <el-input v-model="editForm.price" type="number" autocomplete="off"></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="套餐名称" label-width="100px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.id==0?'添 加':'修 改' }}</el-button>
      </div>
    </el-dialog>










  </div>
</template>




<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {addGoPhotograph} from "../../../api/go_photograph.js"
import {getToken} from "../../../common/utils/auth";


export default {
  name: "goPhotograph",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      taskItems:[],
      doneFormVisible:false,
      showAddItemDialog: false,
      fileList:[],
      addItemForm:{
        items:[]
      },
      addItems:[],
      doneRow: '',

      editForm: {
        id: 0,
        name:'',
        itemName:'',
        serialNumber:'',
        carTypeId: '',
        testProductTypeId:'',
        testItemIdListTemp: [],
        testItemIdList: [],
        testItemIdsList: [],
        // price:'',
        note: '', // 备注
        productTypeId1:'',
        productTypeId2:'',
        testItems:[],
        fileList:[],
      },
      editRules: {
        serialNumber: [{ required: true, message:"请输入员工编号", trigger: 'blur'}],

      },
      loadingDiv: null,
      searchForm: {

      },
      excelImp: {
        dialogVisible: false,
        loading: false,
        fileList:[],
        action: '',
        loadingDiv:'',
      },
      carTypeList: [],
      testProductTypeList: [],
      testItemList: [],



      baseUrl: '',
      uploadActionUrl: '',
      avatarUploadLoadingDiv: '',

      tabsActiveName: '',
      xctpDialogVisible:false,
      xctpImg:'',
      xctpRow:'',


    }
  },
  watch:{

  },
  mounted() {
    this.init();
    // this.getDataList(this.currentPage);


    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }

    let t = getToken();
    this.uploadActionUrl = this.$adminApiUrl + "/file/upload?_t="+t;
    this.fileBaseUrl = this.$adminApiUrl+"/file/get?_t="+t+"&f=";
  },
  methods: {



    parseItem(row){

      let itemList = row.itemList;

      let str = "";
      for(let i in itemList) {
        let item = itemList[i];
        if(item.level == 2) {
          str += item.serialNumber + "/" + item.itemName + "<br>";
        }else if(item.level == 3){
          str += item.serialNumber + "/" + item.parentItemName + "/" + item.itemName + "<br>";
        }
      }

      return str;
    },
    handlePreview(file) {
            // console.log(file);
          },
    // beforeRemove(file, fileList) {
    //     return this.$confirm(`确定移除 ${ file.name }？`);
    //   },
    handleRemove(file, fileList) {

      this.fileList = fileList;
      let data = [];
      // console.log(this.fileList.length)
      for(var i=0;i<this.fileList.length;i++){

        // console.log(fileList[i].response.data)
        data.push(fileList[i].response.data)
      }
      this.editForm.fileList = data;
      // this.editForm.fileList = fileList;

            // console.log(file, fileList);
      },
      handleAvatarSuccess(res, file, fileList){
        // console.log("12")
        // this.avatarUploadLoadingDiv.close();
        if (res.code == 1){
          this.fileList = fileList;
          let data = [];
          // console.log(this.fileList.length)
          for(var i=0;i<this.fileList.length;i++){

            // console.log(fileList[i].response.data)
            if(fileList[i].response!=null&&fileList[i].response!=''){
              data.push(fileList[i].response.data)
            }
          }
          this.editForm.fileList = data;
          // console.log(this.editForm.fileList)
          // this.fileList = fileList;
          // console.log("++++++++++++++++++");
          // console.log(this.editForm.fileList);
          // console.log(this.res.data);
          // console.log("++++++++++++++++++");
          return;
        }else{
          this.$message({
            message: res.msg,
            type: 'warning'
          });
        }
      },

    init(){

      // 获取所有车辆类型
      // getAllCarTypeList().then(res => {
      //   if(res.code == 1) {
      //     this.carTypeList = res.data;
      //   }
      // }).catch(res => {

      // });

      // 获取所有检测产品类别
      // getAllTestProductTypeList().then(res => {
      //   if(res.code == 1) {

      //     this.testProductTypeList = res.data;
      //   }
      // }).catch(res => {

      // });



      // 获取检测项目
    //   getTestItemList().then(res => {
    //     if(res.code == 1) {
    //       this.testItemList = res.data;
    //     }
    //   }).catch(res => {

    //   });


    },

    addToTaskItems(){
      if(this.addItemForm.items && this.addItemForm.items.length > 0 ){
        this.taskItemsMerge();
      }

      this.showAddItemDialog = false;
    },


    getItem(itemId){
      for(let i in this.addItems){
        if(itemId == this.addItems[i].tId || itemId == this.addItems[i].id){
          return this.addItems[i];
        }
      }
    },


    taskItemsMerge(){
      // console.log("1")

      const testItems = this.editForm.testItems;
      if(this.editForm.testItems==null||this.editForm.testItems==''){
        this.editForm.testItems = [];
      }

      for(let i in this.addItemForm.items){
        let addItem = this.getItem(this.addItemForm.items[i]);
        if(util.isEmpty(addItem)){
          continue;
        }
        let inFlag = false;
        for(let j in testItems){
          if(addItem.tId == testItems[j].itemTId){
            inFlag = true;
            break;
          }
        }
        if(addItem && !inFlag){
          let ii = {
            id: addItem.id,
            itemTId: addItem.tId,
            itemName: addItem.itemName,
            serialNumber: addItem.serialNumber,
            num: 1,
          }
          this.editForm.testItems.push(ii);
        }
      }
    },


    loadTestItems(fn){
      this.addItems = [];

      const loadingDiv = util.showLoading("加载中...")
      const param = {
        carTypeId: this.editForm.carTypeId,
        productTypeId1: this.editForm.testProductTypeId[0],
        productTypeId2: this.editForm.testProductTypeId[1],
      }

      getTestItemList2(param).then(res=>{
        loadingDiv.close();
        if(res.code == 1){
          //this.addItems = res.data;
          let arr = [];
          let data = res.data;

          for(let i in data){
            let item = data[i];
            item['label'] = item.serialNumber + "-" + item.itemName;
            arr.push(item)
          }

          this.addItems = arr;

          if(fn){
            fn();
          }
        }else{
          this.$message({
            showClose: true,
            message: "加载检测项目失败",
            type: 'error'
          });
        }
      }).catch(err=>{
        loadingDiv.close();
      });
    },


    showChoseItemDialog(){
      if(util.isEmpty(this.editForm.carTypeId)){
        this.$message({
          showClose: true,
          message: "请先选择车型类别",
          type: 'error'
        });
        return;
      }
      if(util.isEmpty(this.editForm.testProductTypeId)
      ){
        this.$message({
          showClose: true,
          message: "请先选择申报类型",
          type: 'error'
        });
        return;
      }


      this.addItemForm.items=[];
      this.loadTestItems();


      this.showAddItemDialog = true;

    },

    showAddDialogForm() {
      this.editForm.fileVideoList = [];
      this.editForm.fileList = [];
      this.fileList = [];
      this.fileVideoList = [];
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = '';
      }

      this.editForm.testItemIdList = [];
      this.editForm.id = 0
      this.editFormVisible = true;
    },
    handleEdit(index, row) {

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = row[key];
      }

      this.editForm.testProductTypeId = [row.productTypeId1,row.productTypeId2];

      // console.log(row)

      let param = {}

      param['id']=row.id;
      // console.log(param)

        getTestGroupItem(param).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          //this.testItemIdListTemp = data;
          this.testItemList = res.data;
          this.editForm.testItems = this.testItemList;
        }
      })


      this.editFormVisible = true;



    },



    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {

          // 参数处理
          let param={

          };

          param['id'] = this.editForm.id;
          param['url'] = this.editForm.fileList[0];






          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.id){
            loadingText = "修改中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = addGoPhotograph
          func(param).then(res => {
            let title = "修改"
            if(this.editForm.id == 0){
              title = "添加"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  // this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.name+"打包项目"+"?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteTestGroup({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              // this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },

    testGroupItems(index, row){
      // console.log(row);
      getTestGroupItem({id: row.id}).then(res=>{
        // console.log(res)
        if(res.code == 1){
          this.taskItems = res.data;

          this.doneRow = row;

          this.doneFormVisible=true;
        }else{
          this.$message.error("加载信息失败")
        }
      });
      },


    handleExcelImp(){
      this.excelImp.fileList=[];
      this.excelImp.dialogVisible = true;
    },
    onUploadSuccess(res, file, fileList){
      this.excelImp.loading = false;
      this.excelImp.loadingDiv.close();

      if(res.code == 0) {
        this.$alert(res.msg,{dangerouslyUseHTMLString:true,type:'warning'})
      }else if(res.code == 1) {
        this.$alert(res.msg,{dangerouslyUseHTMLString:true,type:'success'})
          .then(()=> {
            // this.getDataList(1);
            this.excelImp.dialogVisible=false;
          })
      }
    },
    onUploadError(err, file, fileList){
      this.excelImp.loading = false;
      this.excelImp.loadingDiv.close();
      this.$alert("导入失败",{dangerouslyUseHTMLString:true,type:'warning'})
    },
    submitUpload() {
      this.excelImp.loading = true;
      this.excelImp.loadingDiv = util.showLoading("导入中")
      this.$refs.upload.submit();
    },
    handleExcelImp(){
      this.excelImp.fileList=[];
      this.excelImp.dialogVisible = true;
    },




    // getDataList(pageNum){
    //   const loadingDiv = util.showLoading()

    //   getTestGroupList({
    //     pageSize: this.pageSize,
    //     pageNum: pageNum,
    //   }).then(res => {
    //     if(res.code == 0) {
    //       this.$message({
    //         showClose: true,
    //         message: res.msg,
    //         type: 'error'
    //       });
    //     }else if(res.code == 1) {
    //       let data = res.data.records;
    //       this.currentPage = pageNum;
    //       this.total = res.data.total;
    //       this.tableData = data;
    //     }
    //     loadingDiv.close();
    //   }).catch(res => {
    //     loadingDiv.close();
    //   })
    // },
    search() {
      // this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            // this.pageSize = pageSize;
            // this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            // this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
  .test-item-table{
    width: 80%;
    border-collapse: collapse;

    th, td {
      width: 33.3%;
      text-align: center;
      border: 1px solid #CCC;
    }
  }

  .test-item-table{
    width: 100%;
    border-collapse: collapse;
    tr{
      height: 40px;
    }

    th, td {
      width: 33%;
      text-align: center;
      border: 1px solid #CCC;
    }
    th {
      background-color: #EDF2FC;
    }
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
